package com.example.s7;

import HslCommunication.Profinet.Siemens.SiemensPLCS;
import HslCommunication.Profinet.Siemens.SiemensS7Net;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

/**
 * Copyright: Copyright (c) 2022
 * 二标段PLC连接工厂，PLC的版本是400
 * <p>
 * Description:
 *
 * @author LiuFeng
 * @version 2022/11/21 12:08
 * @since
 */
@Slf4j
public class PlcSectionTwoConnectorFactory extends BasePooledObjectFactory<SiemensS7Net> {
    private static volatile GenericObjectPool<SiemensS7Net> pool = null;

    private static final String IP_ADDRESS = "172.18.1.101";

    public static GenericObjectPool<SiemensS7Net> getInstance() {
        if (pool == null) {
            synchronized (PlcSectionTwoConnectorFactory.class) {
                if (pool == null) {
                    int processors = Runtime.getRuntime().availableProcessors();
                    GenericObjectPoolConfig<SiemensS7Net> config = new GenericObjectPoolConfig<>();
                    config.setMaxTotal(-1);
                    config.setMaxIdle(processors * 2 * 2);
                    config.setMinIdle(processors * 2);
                    config.setLifo(false);
                    pool = new GenericObjectPool<>(new PlcSectionTwoConnectorFactory(), config);
                }
            }
        }
        return pool;
    }

    @Override
    public SiemensS7Net create() throws Exception {
        SiemensS7Net siemensS7Net = new SiemensS7Net(SiemensPLCS.S400, IP_ADDRESS);
        siemensS7Net.ConnectServer();
        siemensS7Net.SetPersistentConnection();
        return siemensS7Net;
    }

    @Override
    public PooledObject<SiemensS7Net> wrap(SiemensS7Net siemensS7Net) {
        return new DefaultPooledObject<>(siemensS7Net);
    }

    public static void clear() {
        getInstance().clear();
    }

    public static void close() {
        getInstance().close();
    }

    public static SiemensS7Net borrowObject() throws Exception {
        return getInstance().borrowObject();
    }

    public static void returnObject(SiemensS7Net context) throws Exception {
        getInstance().returnObject(context);
    }

    @Override
    public void passivateObject(PooledObject<SiemensS7Net> p) throws Exception {
        super.passivateObject(p);
//        log.info("连接池中对象数量：{}", pool.getCreatedCount());
    }

    @Override
    public void destroyObject(PooledObject<SiemensS7Net> p) throws Exception {
        log.info("销毁对象：{}", p.getObject().getIpAddress());
        p.getObject().ConnectClose();
    }
}
